
from django.shortcuts import render, redirect, get_object_or_404
from LogisticsCard.models import SystemConfig
from django.contrib import messages
from django.urls import reverse
from django.views.decorators.http import require_POST
from django.utils import timezone

def system_config_list_view(request):
    configs = SystemConfig.objects.all()
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    paginator = Paginator(configs, 10)
    page = request.GET.get('page')
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    return render(request, 'system_config_manage/index.html', {'page_obj': page_obj})

def system_config_create_view(request):
    if request.method == 'POST':
        name = request.POST.get('name', '')
        key = request.POST.get('key', '')
        value = request.POST.get('value', '')
        type = request.POST.get('type', 1)
        options = request.POST.get('options', '')
        remark = request.POST.get('remark', '')
        SystemConfig.objects.create(name=name, key=key, value=value, type=type, options=options, remark=remark)
        messages.success(request, '添加成功')
        return redirect(reverse('system_config_manage'))
    return render(request, 'system_config_manage/create.html')

def system_config_edit_view(request, config_id):
    config = get_object_or_404(SystemConfig, pk=config_id)
    if request.method == 'POST':
        config.name = request.POST.get('name', config.name)
        config.key = request.POST.get('key', config.key)
        config.value = request.POST.get('value', config.value)
        config.type = request.POST.get('type', config.type)
        config.options = request.POST.get('options', config.options)
        config.remark = request.POST.get('remark', config.remark)
        config.save()
        messages.success(request, '修改成功')
        return redirect(reverse('system_config_manage'))
    return render(request, 'system_config_manage/edit.html', {'config': config})

@require_POST
def system_config_delete_view(request, config_id):
    config = get_object_or_404(SystemConfig, pk=config_id)
    config.delete_at = timezone.now()
    config.save()
    messages.success(request, '删除成功')
    return redirect(reverse('system_config_manage'))
